package com.ioftv.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ioftv.common.Result;
import com.ioftv.dto.ImportResultDTO;
import com.ioftv.dto.PageResult;
import com.ioftv.dto.ProjectInfoExcelDTO;
import com.ioftv.entity.ProjectInfo;
import com.ioftv.listener.ProjectInfoImportListener;
import com.ioftv.service.ProjectInfoService;
import com.ioftv.util.UserContextUtil;
import com.ioftv.util.RolePermissionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据项目实时看板Controller
 * 实现项目信息记录的增删改查、分页查询、Excel导入导出等功能
 */
@Slf4j
@RestController
@RequestMapping("/admin/data-project")
public class ProjectInfoController {

    @Autowired
    private ProjectInfoService projectInfoService;

    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 4.1 分页查询数据项目列表
     * GET /admin/data-project
     */
    @GetMapping
    public Result<PageResult<ProjectInfo>> getPageList(
            @RequestParam Integer currentPage,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String projectName,
            @RequestParam(required = false) Integer projectStatus,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 创建分页对象
        Page<ProjectInfo> page = new Page<>(currentPage, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<ProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            queryWrapper.eq(ProjectInfo::getUserId, userId);
        }
        if (projectName != null && !projectName.trim().isEmpty()) {
            queryWrapper.like(ProjectInfo::getProjectName, projectName);
        }
        if (projectStatus != null) {
            queryWrapper.eq(ProjectInfo::getProjectStatus, projectStatus);
        }
        queryWrapper.orderByDesc(ProjectInfo::getCreateTime);
        
        // 执行分页查询
        Page<ProjectInfo> resultPage = projectInfoService.page(page, queryWrapper);
        
        // 构造返回结果
        PageResult<ProjectInfo> pageResult = new PageResult<>(
            resultPage.getRecords(),
            resultPage.getTotal(),
            currentPage,
            pageSize
        );
        
        return Result.success(pageResult);
    }

    /**
     * 4.2 新增数据项目记录
     * POST /admin/data-project
     */
    @PostMapping
    public Result<ProjectInfo> addProjectInfo(@RequestBody ProjectInfo projectInfo, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        projectInfo.setUserId(userId);
        
        // 参数校验
        if (projectInfo.getProjectName() == null || projectInfo.getProjectName().trim().isEmpty()) {
            return Result.error("项目名称不能为空");
        }
        
        if (projectInfo.getProjectCode() == null || projectInfo.getProjectCode().trim().isEmpty()) {
            return Result.error("项目编号不能为空");
        }
        
        if (projectInfo.getPaymentCycle() == null || projectInfo.getPaymentCycle().trim().isEmpty()) {
            return Result.error("回款周期不能为空");
        }
        
        if (projectInfo.getProjectStatus() == null) {
            projectInfo.setProjectStatus(0); // 默认未开始
        }
        
        if (projectInfo.getDataVolume() == null) {
            projectInfo.setDataVolume(0);
        }
        
        if (projectInfo.getRequiredPersonnel() == null) {
            projectInfo.setRequiredPersonnel(0);
        }
        
        // 验证项目状态范围
        if (projectInfo.getProjectStatus() < 0 || projectInfo.getProjectStatus() > 3) {
            return Result.error("项目状态取值范围：0-未开始 1-进行中 2-已完成 3-已取消");
        }
        
        // 检查项目编号唯一性
        LambdaQueryWrapper<ProjectInfo> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(ProjectInfo::getProjectCode, projectInfo.getProjectCode());
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            checkWrapper.eq(ProjectInfo::getUserId, userId);
        }
        if (projectInfoService.count(checkWrapper) > 0) {
            return Result.error(1006, "项目编号已存在");
        }
        
        // 保存数据
        boolean success = projectInfoService.save(projectInfo);
        if (success) {
            return Result.success(projectInfo);
        } else {
            return Result.error("新增失败");
        }
    }

    /**
     * 4.3 修改数据项目记录
     * PUT /admin/data-project/{id}
     */
    @PutMapping("/{id}")
    public Result<ProjectInfo> updateProjectInfo(@PathVariable Long id, @RequestBody ProjectInfo projectInfo, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        LambdaQueryWrapper<ProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectInfo::getId, id);
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            queryWrapper.eq(ProjectInfo::getUserId, userId);
        }
        
        ProjectInfo existing = projectInfoService.getOne(queryWrapper);
        if (existing == null) {
            return Result.error(404, "数据不存在或无权限访问");
        }
        
        // 设置ID
        projectInfo.setId(id);
        // 保持用户ID不变
        projectInfo.setUserId(existing.getUserId());
        
        // 如果项目编号修改了，检查唯一性
        if (projectInfo.getProjectCode() != null && 
            !projectInfo.getProjectCode().equals(existing.getProjectCode())) {
            LambdaQueryWrapper<ProjectInfo> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.eq(ProjectInfo::getProjectCode, projectInfo.getProjectCode());
            // 添加用户ID条件（管理员可查看所有数据）
            if (!RolePermissionUtil.isAdmin(role)) {
                checkWrapper.eq(ProjectInfo::getUserId, userId);
            }
            if (projectInfoService.count(checkWrapper) > 0) {
                return Result.error(1006, "项目编号已存在");
            }
        }
        
        // 验证项目状态范围
        if (projectInfo.getProjectStatus() != null && 
            (projectInfo.getProjectStatus() < 0 || projectInfo.getProjectStatus() > 3)) {
            return Result.error("项目状态取值范围：0-未开始 1-进行中 2-已完成 3-已取消");
        }
        
        // 更新数据
        boolean success = projectInfoService.updateById(projectInfo);
        if (success) {
            // 重新查询返回最新数据
            ProjectInfo updated = projectInfoService.getOne(queryWrapper);
            return Result.success(updated);
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 4.4 删除数据项目记录
     * DELETE /admin/data-project/{id}
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteProjectInfo(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        LambdaQueryWrapper<ProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectInfo::getId, id);
        // 添加用户ID条件（管理员可查看所有数据）
        if (!RolePermissionUtil.isAdmin(role)) {
            queryWrapper.eq(ProjectInfo::getUserId, userId);
        }
        
        ProjectInfo existing = projectInfoService.getOne(queryWrapper);
        if (existing == null) {
            return Result.error(404, "数据不存在或无权限访问");
        }
        
        // 删除数据
        boolean success = projectInfoService.removeById(id);
        if (success) {
            return Result.success(null);
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 4.5 下载Excel导入模板
     * GET /admin/data-project/template
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据项目导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 创建空模板（只有表头）
            List<ProjectInfoExcelDTO> templateData = new ArrayList<>();

            // 写入Excel（只生成表头，不含数据）
            EasyExcel.write(response.getOutputStream(), ProjectInfoExcelDTO.class)
                    .sheet("数据项目数据")
                    .doWrite(templateData);

            log.info("下载Excel模板成功");
        } catch (IOException e) {
            log.error("下载Excel模板失败", e);
            throw new RuntimeException("下载模板失败: " + e.getMessage());
        }
    }

    /**
     * 4.6 批量导入Excel数据
     * POST /admin/data-project/import
     */
    @PostMapping("/import")
    public Result<ImportResultDTO> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要导入的文件");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return Result.error("仅支持Excel文件格式（.xlsx或.xls）");
        }

        try {
            log.info("开始导入Excel文件: {}", fileName);

            // 创建导入结果对象
            ImportResultDTO importResult = new ImportResultDTO();

            // 使用监听器模式读取Excel，支持大文件
            ProjectInfoImportListener listener = new ProjectInfoImportListener(projectInfoService, importResult);
            listener.setUserId(userId); // 设置用户ID用于数据隔离
            
            EasyExcel.read(file.getInputStream(), 
                          ProjectInfoExcelDTO.class, 
                          listener)
                    .sheet()
                    .doRead();

            log.info("导入完成: 总行数={}, 成功={}, 失败={}", 
                    importResult.getTotalRows(), 
                    importResult.getSuccessRows(), 
                    importResult.getFailRows());

            return Result.success(importResult);

        } catch (IOException e) {
            log.error("导入Excel文件失败", e);
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("导入Excel文件异常", e);
            return Result.error("导入异常: " + e.getMessage());
        }
    }
}